<template>
  <div class="search-bar">
    <div class="search-bar-wrapper" @click="onSearchBarClick">
      <van-icon name="search" class="search" size="16px" color="#858C96"/>
      <input type="text" class="search-bar-wrapper-input"
      :placeholder="hotSearch.length === 0 ? '搜索' : hotSearch "
      :focus="focus" :disabled="disabled"
      :maxlength="limit" v-model="searchWord" @input="onChange"
      confirm-type="search" @confirm="onConfirm"
      placeholder-style="color: #ADB4BE"/>
      <van-icon name="clear" class="clear" size="16px" color="#ccc" @click="onClearClick"
      v-if="searchWord.length > 0"/>
    </div>

  </div>
</template>

<script>
export default {
  props: {
    // 搜索框是否获得焦点
    focus: {
      type: Boolean,
      default: true
    },
    // 搜索框是否可交互
    disabled: {
      type: Boolean,
      default: false
    },
    // 搜索框最大可输入字符数
    limit: {
      type: Number,
      default: 10
    },
    // 热门搜索词
    hotSearch: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      // 搜索关键字
      searchWord: ''
    }
  },
  methods: {
    // 搜索框点击事件
    onSearchBarClick () {
      this.$emit('onClick')
    },
    // 点击清空事件
    onClearClick () {
      this.searchWord = ''
      this.$emit('onClear')
    },
    // 输入监听事件
    onChange (e) {
      const { value } = e.mp.detail
      this.$emit('onChange', value)
    },
    // 点击虚拟键盘搜索事件
    onConfirm (e) {
      const { value } = e.mp.detail
      this.$emit('onConfirm', value)
    },
    // 对输入框关键字赋值
    setValue (v) {
      this.searchWord = v
    },
    // 获取输入框的关键字
    getValue () {
      return this.searchWord
    }
  }
}
</script>

<style lang="scss" scoped>
  .search-bar{
    padding: 15px 15.5px;

    &-wrapper{
      height: 40px;
      box-sizing: border-box;
      display: flex;
      flex-direction: row;
      background-color: rgb(242, 242, 243) ;
      border-radius: 20px;
      align-items: center;
      padding: 12px 17px;
      .search, .clear{
        display: flex;
        align-items: center;
        height: 100%;
      }
      &-input{
        flex: 1;
        margin: 0 8px;
        color: #333;
        font-size: 15px;
      }
    }
  }
</style>
